<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\api\model\Attention;
use app\api\model\BlackList;
use app\api\model\Interaction;
use app\api\model\SeeMe;
use app\api\model\UserInfo;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'getAvatar'];
    protected $noNeedRight = '*';

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $source = input('source');
        $identification = input('identification');
        if ($source && $identification) {
            $where = [];
            switch ($source) {
                case 'qq':
                    $where['qq'] = $identification;
                    break;
                case 'we_chat':
                    $where['we_chat'] = $identification;
                    break;
                case 'ios':
                    $where['ios'] = $identification;
                    break;
            }
            if (!$where) $this->error('参数错误');
            $user = \app\admin\model\User::get($where);
            if (!$user) {
                $info['source'] = input('source');
                $info['identification'] = input('identification');
                $this->success('未注册', $info);
            }
            $ret = $this->auth->direct($user->id);
        } else {
            $account = input('account');
            $password = input('password');
            if (!$account || !$password) {
                $this->error(__('Invalid parameters'));
            }
            $ret = $this->auth->login($account, $password);
        }
        if ($ret) {
            $data = $this->auth->getUserinfo();
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 添加个人信息
     */
    public function userinfo()
    {
        $param = input();
        $user_info = UserInfo::get(['user_id' => $this->uid]);
        if ($user_info) {
            if (input('username') || input('avatar')) {
                $ry = new RongYun();
                $user['id'] = $this->uid;
                $user['name'] = input('username');
                $user['portrait'] = input('avatar');
                $ry_data = $ry->updateRefresh($user);
                if ($ry_data['code'] != 200) {
                    $this->error('融云信息更改失败！');
                }
            }
            UserInfo::update($param, ['user_id' => $this->uid]);
            $this->success('修改成功!五分钟内生效', UserInfo::get(['user_id' => $this->uid]));
        }
        $param['user_id'] = $this->uid;
        if (!input('username') || !input('avatar')) {
            $this->error('参数不全');
        }
        $user['id'] = $this->uid;
        $user['name'] = $param['username'];
        $user['portrait'] = $param['avatar'];
        $ry = new RongYun();
        $ry_data = $ry->register($user);
        if ($ry_data['code'] == 200) {
            model('user')->where('id', $this->uid)->update(['ry_token' => $ry_data['token']]);
        } else {
            $this->error('获取ry_token失败！请联系管理员');
        }
        $data = UserInfo::create($param);
        $data['ry_token'] = $ry_data['token'];
        $this->success('添加成功', $data);
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = input('mobile');
        $captcha = input('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = $this->auth->getUserinfo();
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $password = input('password');
        $mobile = input('mobile');
        $code = input('code');
        $invitationCode = input('invitationCode');
        if (!$mobile || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($mobile, $password, '', $mobile, ['invitation_code' => $invitationCode]);
        if ($ret) {
            $data = $this->auth->getUserinfo();
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = input('username');
        $nickname = input('nickname');
        $bio = input('bio');
        $avatar = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        if ($avatar) {
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = input('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = input('mobile');
        $captcha = input('captcha');
        $newMobile = input('newMobile');
        $newCaptcha = input('newCaptcha');
        if (!$mobile || !$captcha || !$newMobile || !$newCaptcha) {
            $this->error(__('无效参数'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$") || !Validate::regex($newMobile, "^1\d{10}$")) {
            $this->error(__('手机号格式不正确'));
        }
        if (\app\common\model\User::where('mobile', $newMobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('已存在该手机号'));
        }
        if (Admin::where('username', $newMobile)->where('user_id', '<>', $user->id)->find()) {
            $this->error(__('已存在该手机号的店铺'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('原手机号验证码不正确'));
        }
        $newResult = Sms::check($newMobile, $newCaptcha, 'changemobile');
        if (!$newResult) {
            $this->error(__('新手机号验证码不正确'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $newMobile;
        $admin = Admin::get(['user_id' => $this->uid]);
        if ($admin) {
            $admin->username = $newMobile;
            $admin->save();
        }
        $user->save();
        Sms::flush($newMobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = input("platform");
        $code = input("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $mobile = input("mobile");
        $newpassword = input("newpassword");
        $captcha = input("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改密码
     *
     */
    public function resetPassword()
    {
        $password = input("password");
        $newpassword = input("newpassword");
        $user = $this->auth->getUser();
        if (md5(md5($password) . $user->salt) == $user->password) {
            $new = $this->auth->getEncryptPassword($newpassword, $user->salt);
            $user->password = $new;
            $user->save();
            $this->success('密码修改成功');
        }
        $this->error('原密码错误');
    }

    /**
     * 绑定第三方
     */
    public function party()
    {
        $identification = input('identification');
        $source = input('source');
        if (!$identification || !$source) {
            $this->error('参数错误');
        }
        $data = model('user')->where($source, $identification)->find();
        if ($data) {
            $this->error('已绑定其他账号');
        }
        $user = $this->auth->getUser();
        if ($source == 'we_chat') {
            $user->we_chat = $identification;
        } else if ($source == 'qq') {
            $user->qq = $identification;
        } else {
            $this->error('source参数不规范');
        }
        $this->success('绑定成功', $user->save());
    }

    /**
     * 身份认证
     */
    public function authentication()
    {
        $param = input();
        $param['status'] = 0;
        $this->success('成功', UserInfo::update($param, ['user_id' => $this->uid]));
    }

    /**
     *
     * 加入黑名单
     */

    public function addBlack()
    {
        $param['black_id'] = input('black_id');
        $param['user_id'] = $this->uid;
        if (BlackList::get($param)) $this->success('已移入黑名单');
        $RongYun = new RongYun();
        $result = $RongYun->blackAdd($param);
        if ($result['code'] == 200) {
            $this->success('成功', BlackList::create($param));
        }
        $this->error('添加失败');
    }

    /**
     *
     * 移除黑名单
     */

    public function delBlack()
    {
        $param['black_id'] = input('black_id');
        $param['user_id'] = $this->uid;
        $RongYun = new RongYun();
        $result = $RongYun->blackRemove($param);
        if ($result['code'] == 200) {
            $this->success('成功', BlackList::destroy($param));
        }
        $this->error('移除失败');
    }

    /**
     *
     * 黑名单列表
     */

    public function blackList()
    {
        $this->success('成功', model('black_list')->blackList($this->uid));
    }

    /**
     *
     * 好友验证
     */

    public function friendsVer()
    {
        $param['friends_ver'] = input('status');
        $this->success('成功', \app\api\model\User::update($param, ['id' => $this->uid]));
    }

    /**
     *
     * 关注
     */

    public function attention()
    {
        $attention = input('status');
        $param['user_id'] = $this->uid;
        $param['attention_id'] = input('attention_id');
        if ($param['user_id'] == $param['attention_id']) $this->error('不能关注自己');
        if ($attention == 0) {
            $this->success('取关成功', Attention::destroy($param));
        } else if ($attention == 1) {
            $data = Attention::create($param);
            //添加互动消息
            $inter['user_id'] = input('attention_id');
            $inter['object_id'] = $this->uid;
            $inter['type'] = 1;//类型  加好友
            $inter['status'] = 0;// 申请状态
            Interaction::create($inter);
            $data['attention'] = attention($param['user_id'], $param['attention_id']);//返回关注状态
            $this->success('关注成功', $data);
        }
        $this->error('关注失败');
    }

    /**
     *
     * 他的主页
     */

    public function homePage()
    {
        $user_id = $this->uid;
        $home_id = input('user_id');
        if ($home_id > 0) {
            $see['user_id'] = $user_id;
            $see['see_id'] = $home_id;
            $see_me = SeeMe::get($see);
            //判断是否已经访问过（已访问过数量加一）
            if ($see_me) {
                $see_me->num += 1;
                $see_me->save();
            } else {
                model('see_me')::create($see);
            }
        }
        $this->success('成功', model('user_info')->homePage($user_id, $home_id));
    }

    /**
     *
     * 添加好友
     */

    public function addFriends()
    {
        $user_id = $this->uid;
        $friends_id = input('user_id');
        if ($user_id == $friends_id) $this->error('不能添加自己为好友');
        $result = model('user')->addFriends($user_id, $friends_id);
        if ($result) {
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }

    /**
     *
     * 我的信息
     */

    public function myInfo()
    {
        $user_id = $this->uid;
        $this->success('成功', model('user_info')->myInfo($user_id));
    }

    /**
     *
     * 我的交际
     */

    public function myCommunication()
    {
        $user_id = $this->uid;
        $this->success('成功', model('user_info')->myCommunication($user_id, input('type'), input('search')));
    }

    /**
     *
     * 谁看过我
     */

    public function seeMe()
    {
        $user_id = $this->uid;
        $this->success('成功', model('see_me')->seeMe($user_id));
    }

    /**
     * 获取用户头像和昵称
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAvatar()
    {
        $this->success('成功', model('user_info')->where('user_id', input('user_id'))->field('avatar,username')->find());
    }

    /**
     *
     * 互动消息
     */
    public function interaction()
    {
        $this->success('成功', model('interaction')->interactionList($this->uid));
    }
}
